<script setup lang="ts">
import { openExternal } from "@/framework/util/shell";
import { hc } from "@/framework/vue/util/render";
import { CopyOutlined } from "@ant-design/icons-vue";
import ArchiveInstallOperation from "@/pages/tools/components/archive-install-operation.vue";
import { onMounted, ref, shallowRef } from "vue";
import path from "path-browserify-esm";
import type { ToolInstallVersionItem } from "../common/types";
import { useMavenStore } from "@/pages/tools/java/maven-store";
import { copyText } from "@/pages/tools/common/util";
import { getMvndDownloadPath, getMvndFileName, getMvndVersionsViaHuaweiCloud, mvndMirrors } from "@/pages/tools/java/mvnd-api";

const mavenStore = useMavenStore();
const versionList = shallowRef<ToolInstallVersionItem[]>([]);
const loading = ref(false);

onMounted(() => {
  // <mirror-prefix>1.0.2/maven-mvnd-1.0.2-windows-amd64.zip
  loading.value = true;
  getMvndVersionsViaHuaweiCloud()
    .then(list => {
      versionList.value = list.map(it => ({
        id: `mvnd-${it}`,
        name: getMvndFileName(it),
        version: it,
        url: getMvndDownloadPath(mvndMirrors.huaweicloud, it),
      }));
    })
    .finally(() => (loading.value = false));
});

const getSavePath = (it: ToolInstallVersionItem) => path.join(mavenStore.installPath, it.name);
const isInstalled = (it: ToolInstallVersionItem) => !!mavenStore.versionMap[it.version];
const onUnzipComplete = () => mavenStore.scanInstalledMaven();
</script>

<template>
  <div class="full-autoscroll position-relative">
    <div v-if="loading" class="abs-fill flex-center">
      <a-spin spinning />
    </div>
    <template v-else>
      <template v-for="it in versionList" :key="it.name">
        <div class="tool-install-version-item">
          <a-space>
            <span class="hover-underline" @click.prevent="openExternal(it.url)">{{ it.name }}</span>
            <a-button :icon="hc(CopyOutlined)" size="small" type="text" title="复制下载地址" @click="copyText(it.url)" />
          </a-space>
          <archive-install-operation
            :id="it.id"
            :save-path="getSavePath(it)"
            :download-url="it.url"
            :is-installed="isInstalled(it)"
            :complete-args="it"
            :after-unzip-complete="onUnzipComplete"
          />
        </div>
      </template>
    </template>
  </div>
</template>
